package tk.mybatis.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.springboot.mapper.CourseMapper;
import tk.mybatis.springboot.mapper.UserMapper;
import tk.mybatis.springboot.model.Course;
import tk.mybatis.springboot.model.Message;
import tk.mybatis.springboot.model.Resource;
import tk.mybatis.springboot.model.Users;

import java.util.List;

/**
 * Created by  on 2017/4/12.
 */
@Controller
@RequestMapping("/course")
@Transactional
public class CourseController {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/add")
    @ResponseBody
    public Object add(Course obj){
        if(null == obj.getId()) {
            courseMapper.insertSelective(obj);
        }
        else {
            courseMapper.updateByPrimaryKeySelective(obj);
        }
        return new Message();
    }
    @RequestMapping("")
    @ResponseBody
    public Object list(Model model){
        List<Course> courses = courseMapper.selectAll();
        for(Course course:courses){
            course.setTeacherName(userMapper.selectByPrimaryKey(course.getTeacherId()).getName());
        }
        return new Message(courses);
    }
    @RequestMapping("/page")
    public String listPage(Model model){
        List<Course> courses = courseMapper.selectAll();
        for(Course course:courses){
            Users users = userMapper.selectByPrimaryKey(course.getTeacherId());
            if(null!=users) {
                course.setTeacherName(users.getName());
            }
        }
        model.addAttribute("list",courses);
        return "course";
    }
    @RequestMapping("/delete/{id}")
    @ResponseBody
    public Object delete(@PathVariable Integer id){
         courseMapper.deleteByPrimaryKey(id);
        return new Message();
    }


}
